<%= component_fields_for @record do |f| %>
  <h2><%= f.label field %></h2>

  <ul class="nested_attributes" id="<%= "#{field.name}_nested_attributes" %>">
    <% if f.object.send(field.name) -%>
      <%= f.fields_for field.name do |nested_builder| %>
        <li id="<%= "#{field.name}_attributes" %>">
          <% field.children.each do |field| %>
            <%= field.render :form, parent_controller, nested_builder.object, :builder => nested_builder %>
          <% end %>

          <% destroy_nested_record = capture do %>
            <%= nested_builder.hidden_field :_destroy, :value => true %>
            <%= nested_builder.hidden_field :id %>
          <% end.to_s.strip.gsub("\n", ' ') %>

          <%= link_to t('.destroy'), '#',
            :data => {:insert => {
              :content => destroy_nested_record,
              :element => "#{field.name}_marked_for_destroy",
              :remove => "#{field.name}_attributes",
              :show => "#{field.name}_attributes_add"
            }} %>
        </li>
      <% end %>
    <% end -%>
  </ul>

  <div id="<%= field.name %>_marked_for_destroy" style="display: none">
  </div>

  <% new_nested_record = capture do %>
    <%= f.fields_for field.name, field.reflection.klass.new do |nested_builder| %>
      <li id="<%= "#{field.name}_attributes" %>">
        <% field.children.each do |field| %>
          <%= field.render :form, parent_controller, nested_builder.object, :builder => nested_builder %>
        <% end %>

        <%= link_to t('.destroy'), '#',
          :data => {:insert => {:remove => "#{field.name}_attributes", :show => "#{field.name}_attributes_add"}} %>
      </li>
    <% end %>
  <% end.to_s.strip.gsub("\n", ' ') %>

  <%= link_to t('.add'), '#',
    :style => ('display: none' if f.object.send(field.name)), :id => "#{field.name}_attributes_add",
    :data => {:insert => {:content => new_nested_record, :element => "#{field.name}_nested_attributes", :hide => "#{field.name}_attributes_add"}} %>
<% end %>
